package cn.terys.terystransactionclient.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public final class SPManager
{

    public static final String SP_NAME                      = "SPManager";

    public static final String SP_KEY_SERIALNUMBER          = "SERIALNUMBER";
    public static final String SP_KEY_SIGNED_USER_ID        = "SIGNED_USER_ID";
    public static final String SP_KEY_SIGNED_USER_BATCH_NUM = "SIGNED_USER_BATCH_NUM";

    private SPManager()
    {
    }

    public static void clearSerialNumber(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        sp.edit().remove(SP_KEY_SERIALNUMBER).commit();
    }

    public static String generateSerialNumber(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        int number;
        synchronized (SPManager.class)
        {
            number = sp.getInt(SP_KEY_SERIALNUMBER, -1);
            number = number + 1;
            sp.edit().putInt(SP_KEY_SERIALNUMBER, number).commit();
        }
        String numStr = String.valueOf(number);
        int addLen = 6 - numStr.length();
        for (int i = 0; i < addLen; i++)
        {
            numStr = "0".concat(numStr);
        }
        return numStr;
    }

    public static void setUserSignedTag(Context context, String userId, String batchNum)
    {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString(SP_KEY_SIGNED_USER_ID, userId);
        editor.putString(SP_KEY_SIGNED_USER_BATCH_NUM, batchNum);
        editor.commit();
    }

    public static String[] getUserSignedTag(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        return new String[] { sp.getString(SP_KEY_SIGNED_USER_ID, null), sp.getString(SP_KEY_SIGNED_USER_BATCH_NUM, null) };
    }

    public static void clearUserSignedTag(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        sp.edit().remove(SP_KEY_SIGNED_USER_ID).commit();
    }

}
